const reviewModel = require('../models/reviewModel');
const { sendSuccess, sendError } = require('../utils/response');

module.exports = {
  // 添加评论
  async addReview(req, res) {
    try {
      const { id: userId } = req.user;
      const { product_id, order_id, rating, content } = req.body;
      console.log(JSON.stringify({ product_id, order_id, rating, content }));
      
      const images = req.files?.map(file => `/uploads/${file.filename}`).join(',') || '';
      
      if (!product_id || !order_id || !rating) {
        return sendError(res, '缺少必要参数', 400);
      }
      
      if (rating < 1 || rating > 5) {
        return sendError(res, '评分必须在1-5之间', 400);
      }
      
      const reviewId = await reviewModel.addReview(
        userId,
        product_id,
        order_id,
        rating,
        content,
        images
      );
      
      sendSuccess(res, { review_id: reviewId }, '评论添加成功', 200);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 获取商品评论
  async getProductReviews(req, res) {
    try {
      const { product_id } = req.params;
      const { page = 1, limit = 10 } = req.query;
      
      const { reviews, pagination } = await reviewModel.getProductReviews(product_id, page, limit);
      sendSuccess(res, { reviews, pagination });
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 获取用户评论
  async getUserReviews(req, res) {
    try {
      const { id: userId } = req.user;
      const { page = 1, limit = 10 } = req.query;
      
      const { reviews, pagination } = await reviewModel.getUserReviews(userId, page, limit);
      sendSuccess(res, { reviews, pagination });
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 删除评论
  async deleteReview(req, res) {
    try {
      const { id: userId } = req.user;
      const { id } = req.params;
      
      await reviewModel.deleteReview(userId, id);
      sendSuccess(res, null, '评论已删除');
    } catch (err) {
      sendError(res, err.message);
    }
  }
};